package io.agora.tutorials1v1vcall;

import android.Manifest;
import android.app.Activity;
import android.graphics.PorterDuff;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;
import io.agora.rtc.video.VideoEncoderConfiguration;

public class ViedoChatTools {

    private static final String LOG_TAG = ViedoChatTools.class.getSimpleName();

    private static final int PERMISSION_REQ_ID = 22;

    // permission WRITE_EXTERNAL_STORAGE is not mandatory for Agora RTC SDK, just incase if you wanna save logs to external sdcard
    private static final String[] REQUESTED_PERMISSIONS = {Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private Activity activity;
    private RtcEngine mRtcEngine;
    private String agora_app_id;
    private FrameLayout frameLayout;

    private String channel;
    private String option;

    public ViedoChatTools(Activity activity,String agora_app_id,FrameLayout frameLayout) {
        this.activity = activity;
        this.agora_app_id=agora_app_id;
        this.frameLayout=frameLayout;
        initAgoraEngineAndJoinChannel();
    }

    private void initAgoraEngineAndJoinChannel() {
        //初始化RTC模块
        initializeAgoraEngine();
        setupVideoProfile();
        setupLocalVideo();
        joinChannel();
    }



    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
        @Override
        public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setupRemoteVideo(uid);
                }
            });
        }

        @Override
        public void onUserOffline(int uid, int reason) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onRemoteUserLeft();
                }
            });
        }

        @Override
        public void onUserMuteVideo(final int uid, final boolean muted) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onRemoteUserVideoMuted(uid, muted);
                }
            });
        }
    };


    private void setupVideoProfile() {
        mRtcEngine.enableVideo();

//      mRtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_360P, false); // Earlier than 2.3.0
        mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(VideoEncoderConfiguration.VD_640x360, VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
                VideoEncoderConfiguration.STANDARD_BITRATE,
                VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT));
    }

    private void setupLocalVideo() {
        SurfaceView surfaceView = RtcEngine.CreateRendererView(activity.getBaseContext());
        surfaceView.setZOrderMediaOverlay(true);
        frameLayout.addView(surfaceView);
        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, 0));
    }

    private void joinChannel() {
        mRtcEngine.joinChannel(null, channel, option, 0); // if you do not specify the uid, we will generate the uid for you
    }

    private void setupRemoteVideo(int uid) {

        if (frameLayout.getChildCount() >= 1) {
            return;
        }

        SurfaceView surfaceView = RtcEngine.CreateRendererView(activity.getBaseContext());
        frameLayout.addView(surfaceView);
        mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, uid));
        surfaceView.setTag(uid); // for mark purpose
    }

    private void leaveChannel() {
        mRtcEngine.leaveChannel();
    }

    private void onRemoteUserLeft() {
        frameLayout.removeAllViews();
    }

    private void onRemoteUserVideoMuted(int uid, boolean muted) {

        SurfaceView surfaceView = (SurfaceView) frameLayout.getChildAt(0);

        Object tag = surfaceView.getTag();
        if (tag != null && (Integer) tag == uid) {
            surfaceView.setVisibility(muted ? View.GONE : View.VISIBLE);
        }
    }


    private void initializeAgoraEngine() {
        try {
            mRtcEngine = RtcEngine.create(activity.getBaseContext(), agora_app_id, mRtcEventHandler);
        } catch (Exception e) {
            Log.e(LOG_TAG, Log.getStackTraceString(e));

            throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
        }
    }


    public void onDestroy() {
        leaveChannel();
        RtcEngine.destroy();
        mRtcEngine = null;
    }

    public void onLocalVideoMute(Boolean isSelect) {

        mRtcEngine.muteLocalVideoStream(isSelect);


        SurfaceView surfaceView = (SurfaceView) frameLayout.getChildAt(0);
        surfaceView.setZOrderMediaOverlay(!isSelect);
        surfaceView.setVisibility(isSelect ? View.GONE : View.VISIBLE);
    }

    public void onLocalAudioMuteClicked(boolean isSelect) {
        mRtcEngine.muteLocalAudioStream(false);
    }

    public void onSwitchCameraClicked(View view) {
        mRtcEngine.switchCamera();
    }


}
